<?php
if (!defined('ABSPATH')) { exit; }

/**
 * Local AES-256-CBC encrypt/decrypt helpers for caching encrypted feature data.
 */
function spider_encrypt_data($data, string $key) {
    $cipher = 'aes-256-cbc';
    $ivlen = openssl_cipher_iv_length($cipher);
    $iv = openssl_random_pseudo_bytes($ivlen);
    // Serialize to preserve arrays/objects; caller must ensure only safe types
    $plaintext = serialize($data);
    $encrypted = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_ZERO_PADDING, $iv);
    if ($encrypted === false) { return false; }
    // Pack as base64(encrypted::iv) using binary-safe separator
    return base64_encode($encrypted . '::' . $iv);
}

function spider_decrypt_data($packed, string $key) {
    if (!$packed) { return false; }
    $decoded = base64_decode($packed, true);
    if ($decoded === false) { return false; }
    $parts = explode('::', $decoded, 2);
    if (count($parts) !== 2) { return false; }
    list($encrypted, $iv) = $parts;
    $cipher = 'aes-256-cbc';
    $decrypted = openssl_decrypt($encrypted, $cipher, $key, OPENSSL_ZERO_PADDING, $iv);
    if ($decrypted === false) { return false; }
    $data = @unserialize($decrypted);
    return $data !== false || $decrypted === 'b:0;' ? $data : false;
}
